package net.daoke.relation.advice;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import net.daoke.relation.model.ResultData;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@AllArgsConstructor
@RestControllerAdvice(basePackages = "net.daoke.relation", annotations = {RestController.class, Controller.class})
public class ResponseAdvice implements ResponseBodyAdvice<Object> {

    private final ObjectMapper objectMapper;

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        // 判断当前请求是否是 Swagger 相关的请求
        String[] excludePath = {"/swagger-config", "/swagger-resources", "/v2/api-docs", "/v3/api-docs", "/api/v1", "/favicon.ico"};
        for (String path : excludePath) {
            if (serverHttpRequest.getURI().getPath().startsWith(path)) {
                return o;
            }
        }
        if (o instanceof ResultData<?>) {
            return o;
        }
        if (o instanceof String) {
            return objectMapper.writeValueAsString(ResultData.success(o));
        }
        return ResultData.success(o);
    }
}
